package it.polito.let.jhp.form;

import it.polito.let.jhp.SemanticException;
import it.polito.let.jhp.types.TypeList;

import java.io.Serializable;
import java.util.*;

public class JHPForm implements Serializable {

	private transient String javaStatement;
	private static final long serialVersionUID = -2929475987442202839L;
	private Map<String, TypeList> symbolTable;
	private int id;
	private FormNode mandatoryTree;

	private List<String> html = new LinkedList<String>();


	public JHPForm () {
		symbolTable = new HashMap<String, TypeList>();
		mandatoryTree = new InputAggregator();
	}

	public int getId () {
		return id;
	}

	public void setId (int n) {
		id=n;
	}	

	public FormNode getTree() {
		return mandatoryTree;
	}

	public Map<String, TypeList> getSymbolTable () {
		return symbolTable;
	}

	public void setJavaStatement(String s) {
		javaStatement = s.trim().substring(2, s.length()-2);
	}

	public String getJavaStatement () {
		return javaStatement;
	}

	public void addHtml(String s)
	{
		html.add(s);
	}

	public void addSymbol (String name, TypeList type) throws SemanticException {
		if (symbolTable.containsKey(name))
			throw new SemanticException("Symbol "+name+" has already been declared for this form");
		symbolTable.put(name,type);
	}

	public String toString()
	{		
		StringBuffer s = new StringBuffer();
		String funcName="_checkForm"+id;
		if (System.getProperty("clientside.check", "false").equalsIgnoreCase("true")) {
			s.append(clientSideCheck(funcName));
			s.append("<form method=\"post\" onSubmit=\"return "+funcName+"(this);\">\r\n");
		} else {
			s.append("<form method=\"post\">\r\n");
		}
		s.append("<input type=\"hidden\" name=\"formid\" value=\""+id+"\">\r\n");
		for(String l:html)
		{	
			l.replaceAll("\\t", "");
			s.append(l);
		}

		s.append("</form>\r\n");
		return s.toString();
	}

	private String clientSideCheck(String funcName) {
		StringBuffer result = new StringBuffer(
				"<script type='text/javascript' src='functions.js'></script>\r\n" +
				"<script language=\"javascript\">\r\n" +
				"function "+funcName+"(form) {\r\n" +
				"for (var i=0; i<form.length; i++) {\r\n" +
		"switch(form.elements[i].name) {\r\n");
		for (String k:symbolTable.keySet()) {
			TypeList t = symbolTable.get(k);
			if (t != null) {
				result.append("case \""+k+"\":\r\n");
				result.append("if (!"+t.clientSideCheck("form.elements[i].value")+") {\r\n" +
						"alert(form.elements[i].name +\" is wrong\");\r\n" +
						"return false;\r\n" +
				"}");
				result.append("break;\r\n");

			}
		}
		result.append(		"}\r\n" +
				"}\r\n" +
				"}\r\n" +
		"</script>");
		return result.toString();
	}

}
